package com.party.web.biz.copartner;

import com.party.common.utils.StringUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityInfo;
import com.party.core.model.copartner.BrokerageItem;
import com.party.core.model.copartner.BrokerageStatusEnum;
import com.party.core.model.copartner.CopartnerLevel;
import com.party.core.model.distributor.DistributorDetail;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.member.Member;
import com.party.core.service.activity.IActivityInfoService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.copartner.IBrokerageItemService;
import com.party.core.service.copartner.ICopartnerLevelService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.member.IMemberService;
import com.party.notify.notifyPush.officialPartner.ICopartnerNotifySendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @program: party
 * @description:
 * @author: Hua Qunhao
 * @create: 2019-09-10 18:30
 **/
@Service
public class BrokerageBizService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IDistributorDetailService distributorDetailService;
    @Autowired
    private IDistributorRelationService distributorRelationService;
    @Autowired
    private IActivityInfoService activityInfoService;
    @Autowired
    private ICopartnerLevelService copartnerLevelService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IBrokerageItemService brokerageItemService;
    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;
    @Autowired
    private ICopartnerNotifySendService copartnerNotifySendService;

    /**
     * 插入佣金记录
     *
     * @param targetId      目标id
     * @param activityId    众筹项目id
     * @param brokerageType 佣金类型
     * @throws Exception
     */
    public void insertBrokerageItem(String targetId, String activityId, Integer brokerageType, String targetAuthorId) throws Exception {
        // 一级分成
        // detail为空，说明众筹不是从分销来的。正常报名的众筹是没有分销数据的。
        DistributorDetail detail = distributorDetailService.findByTargetId(targetId);
        if (null != detail) {
            DistributorRelation relation = distributorRelationService.get(detail.getDistributorRelationId());
            if (null != relation && (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(relation.getType())
                    || DistributorRelationType.COURSE_DISTRIBUTION.getCode().equals(relation.getType()))) {
                ActivityInfo activityInfo = activityInfoService.findByActivityId(activityId);
                if (null == activityInfo || new Integer(0).equals(activityInfo.getIsDistribution())) {
                    throw new Exception("该活动没有配置佣金");
                }
                // 是否可提现
                boolean isBegin = false;
                if (null != activityInfo.getWithdrawDate() && activityInfo.getWithdrawDate().before(new Date())) {
                    isBegin = true;
                }

                CopartnerLevel copartnerLevel = copartnerLevelService.findByMemberId(relation.getDistributorId());
                if (null == copartnerLevel) {
                    throw new Exception("该合伙人不在关系表中");
                }

                Member targetAuthor = memberService.get(targetAuthorId);

                Activity activity = activityService.get(activityId);

                BrokerageItem item = new BrokerageItem();
                item.setBrokerage(activityInfo.getDirectBrokerage().floatValue()); // 一级分成佣金
                item.setCheckStatus(BrokerageStatusEnum.TWO_WITHDRAW.getCode()); // 审核通过
                item.setTargetId(targetId);
                item.setPartnerId(copartnerLevel.getMemberId()); // 分销者
                item.setParentId("-1");
                item.setActivityId(activityId);
                item.setType(brokerageType);
                item.setWithdrawDate(activityInfo.getWithdrawDate());
                brokerageItemService.insert(item);

                try {
//                    Double withdrawalTotal = withdrawalsBizService.getWithdrawalTotal(copartnerLevel.getMemberId(), Withdrawals.TYPE_BROKERAGE);
                    // 修改统计数
                    memberCopartnerDetailBizService.updateBrokerage(copartnerLevel.getMemberId(), activityInfo.getDirectBrokerage(),
                            false, isBegin, 0);
                } catch (Exception e) {
                    logger.error("统计佣金异常", e);
                }

                try {
                    copartnerNotifySendService.sendDirectBrokerage(copartnerLevel.getMemberId()
                            , activity.getTitle(), activityInfo.getDirectBrokerage()
                            , activityId, targetAuthor.getRealname(), brokerageType);
                } catch (Exception e) {
                    logger.error("直接佣金推送异常", e);
                }

                if (StringUtils.isNotEmpty(copartnerLevel.getParentId())) {
                    // 二级分成
                    item = new BrokerageItem();
                    item.setBrokerage(activityInfo.getIndirectBrokerage().floatValue()); // 二级分成佣金
                    item.setCheckStatus(BrokerageStatusEnum.TWO_WITHDRAW.getCode()); // 审核通过
                    item.setTargetId(targetId);
                    item.setPartnerId(copartnerLevel.getMemberId()); // 分销者
                    item.setParentId(copartnerLevel.getParentId()); // 来自下级
                    item.setActivityId(activityId);
                    item.setType(brokerageType);
                    item.setWithdrawDate(activityInfo.getWithdrawDate());
                    brokerageItemService.insert(item);

                    try {
//                        Double withdrawalTotal = withdrawalsBizService.getWithdrawalTotal(copartnerLevel.getParentId(), Withdrawals.TYPE_BROKERAGE);
                        // 修改统计数
                        memberCopartnerDetailBizService.updateBrokerage(copartnerLevel.getParentId(), activityInfo.getIndirectBrokerage(), true, isBegin, 0);
                    } catch (Exception e) {
                        logger.error("统计佣金异常", e);
                    }

                    try {
                        Member member = memberService.get(copartnerLevel.getMemberId());
                        copartnerNotifySendService.sendIndirectBrokerage(copartnerLevel.getParentId()
                                , activity.getTitle(), activityInfo.getIndirectBrokerage()
                                , member.getRealname(), brokerageType);
                    } catch (Exception e) {
                        logger.error("间接佣金推送异常", e);
                    }
                }
            }
        }
    }
}
